import {
  Injectable,
  ExecutionContext,
  CallHandler,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Reflector } from '@nestjs/core';

export interface Response<T> {
  code: number;
  message: string;
  data: T;
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  constructor(private reflector: Reflector) {}

  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    const customMessage = this.reflector.get<string>(
      'response_message',
      context.getHandler(),
    );
    return next.handle().pipe(
      map((data) => ({
        code: 200,
        message: customMessage || '操作成功',
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        data: data !== undefined && data !== null ? data : [],
      })),
    );
  }
}
